package com.code2roc.fastboot.context;

import com.code2roc.fastboot.framework.util.ClassPathFileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.InputStreamResource;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;

public class BootContextInitializer implements ApplicationContextInitializer {
    private static Logger log = LoggerFactory.getLogger(BootContextInitializer.class);

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        log.debug("BootContextInitializer");
        YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        try {
            String frameYAMLFilePath = ClassPathFileUtil.getFilePathActual("systemfile/boot.yml");
            PropertySource<?> propertySource = loader.load("frameConfiguration", new InputStreamResource(new FileInputStream(frameYAMLFilePath))).get(0);
            applicationContext.getEnvironment().getPropertySources().addLast(propertySource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String packageType = applicationContext.getEnvironment().getProperty("system.package");
        if(packageType.equals("war")){
            String active = applicationContext.getEnvironment().getProperty("spring.profiles.active");
            log.debug("LocalConfigContextInit");
            loader = new YamlPropertySourceLoader();
            try {
                URL url = getClass().getClassLoader().getResource("/");
                if(url!=null){
                    String classPath = url.getPath();
                    String rootPath = new File(classPath).getParentFile().getParentFile().getParentFile().getAbsolutePath();
                    File file = new File(rootPath + File.separator + "application-" + active + ".yml");
                    log.debug("Find LocalConfigPath:" + file.getAbsolutePath());
                    if (file.exists()) {
                        String frameYAMLFilePath = file.getAbsolutePath();
                        log.debug("LocalConfig Load Success！");
                        PropertySource<?> propertySource = loader.load("LocalConfigContext", new InputStreamResource(new FileInputStream(frameYAMLFilePath))).get(0);
                        applicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
                    }
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
